import 'package:flutter/material.dart';
import 'package:sample2/components/alert_helper.dart';
import 'package:sample2/helper/app_helper.dart';
import 'package:sample2/model/chat/chat_channel.dart';
import 'package:sample2/model/chat/chat_group.dart';
import 'package:sample2/model/user_info.dart';
import 'package:sample2/pages/chat/chat_group/chat_add_group.dart';
import 'package:sample2/pages/chat/chat_group/chat_group_item.dart';
import 'package:sample2/services/chat_service.dart';

class ChatGroupList extends StatefulWidget {
  const ChatGroupList({super.key});
  @override
  State<StatefulWidget> createState() {
    return ChatGroupState();
  }
}

class ChatGroupState extends State {
  List<ChatGroup> groups = [];
  ChatChannel? _channel;

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    _getGroups();
    super.didChangeDependencies();
  }

  void _getGroups() {
    var arguments = (ModalRoute.of(context)!.settings.arguments ?? {}) as Map;
    if (arguments.keys.isNotEmpty && arguments.keys.contains("channel")) {
      _channel = arguments["channel"];
      ChatService.getGroups(_channel?.channelId ?? "")!
          .then((List<ChatGroup> gps) {
        setState(() {
          groups = gps;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Chat Group"),
          actions: [
            IconButton(
                onPressed: () {
                  AppHelper.shared.getUserInfo().then((UserInfo? userInfo) {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (BuildContext context) {
                      return AddChatGroup(
                        channelId: _channel?.channelId ?? "",
                        adminId: userInfo?.userid ?? "",
                        onSuccessCreateGroup: () {
                          _getGroups();
                        },
                      );
                    }));
                  });
                },
                icon: const Icon(Icons.add))
          ],
        ),
        body: ListView.separated(
            itemBuilder: (BuildContext context, int index) {
              ChatGroup group = groups[index];
              return ChatGroupItem(
                chatGroup: group,
              );
            },
            separatorBuilder: (BuildContext context, int index) {
              return const Divider(
                height: 2,
                thickness: 0.5,
                color: Colors.black,
              );
            },
            itemCount: groups.length));
  }
}
